import { getOrderDetail, payOrder, cancelOrder } from '../../model/order';
import { genderMap, steps } from '../../menus/index';
import dayjs from 'dayjs';

Page({
  data: {
    id: '',
    order: null as any,
    steps: steps,
    active: 1,
    canCancel: false
  },
  async payOrder() {
    const res = await payOrder(this.data.id);
    if (res.code === 200) {
      wx.redirectTo({
        url: '/pages/order-detail/order-detail?id=' + this.data.id
      });
    }
  },
  async cancelOrder() {
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单？',
      success: async (res) => {
        if (res.confirm) {
          const res = await cancelOrder(this.data.id);
          if (res.code === 200) {
            wx.redirectTo({
              url: '/pages/order-detail/order-detail?id=' + this.data.id
            });
          }
        }
      }
    });
  },
  async getDetail() {
    const data = await getOrderDetail(this.data.id);
    if (data) {
      data.companion_gender = genderMap[data.companion_gender as 1];

      // 判断是否能取消订单
      // 就诊时间前一天晚上7点前可取消
      const expiredTime = dayjs(data.visiter_time).set('hour', 19);  
      const now = dayjs();
      const isExpired = now.isBefore(expiredTime);

      this.setData({
        order: data,
        active: data.statue,
        canCancel: isExpired
      });
    }
  },
  async onLoad(query) {
    const id = query.id;
    this.setData({
      id
    });
    this.getDetail();
  }
});
